<template>
    <div class="pnl upload-list">
        <div class="item" v-for="(item, index) in uploadList" :key="item.url">
            <template v-if="item.status === 'finished'">
                <a :href="item.url" target="_blank">
                    <img :src="item.url + '_150w'">
                </a>
                <Icon class="btn-close" type="md-close-circle" @click.native="removeUploadItem(index)"></Icon>
            </template>
            <template v-show="item.status !== 'finished'">
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
        </div>
        <Upload
            class="item"
            ref="upload"
            :show-upload-list="false"
            :on-success="onUploadSuccess"
            accept=".png,.jpg,.jpeg,image/png,image/jpg,image/jpeg"
            :format="['jpg','jpeg','png']"
            :max-size="4096"
            :on-format-error="onUploadFormatError"
            :on-exceeded-size="onUploadSizeError"
            type="drag"
            :action="uploadImageUrl"
            v-show="uploadList.length < maxlength">
            <div>
                <Icon type="md-camera"></Icon>
            </div>
        </Upload>
    </div>
</template>

<script>
    import { getOriginData, uploadImageUrl } from '@/util';

    export default {
        props: {
            uploadList: {
                type: Array,
                defualt: []
            },
            maxlength: {
                type: Number,
                default: 5
            }
        },
        data() {
            return {
                uploadImageUrl: uploadImageUrl,
            }
        },
        methods: {
            removeUploadItem (i) {
                this.uploadList.splice(i, 1);
            },
            onUploadSuccess (res, file) {
                if (res.code === 200) {
                    file.url = res.data;
                    this.$Message.success('上传成功');
                    this.uploadList.push(file);
                    let l = this.uploadList.length
                } else {
                    this.$Notice.error({
                        title: '上传失败',
                        desc: res.message
                    });
                    this.$refs.upload.fileList.splice(this.$refs.upload.fileList.length - 1, 1);
                }
            },
            onUploadFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
                });
            },
            onUploadSizeError (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 4M。'
                });
            }
        }
    }
</script>
